<template>
  <div class="containerhome">
    <div class="containertop">
      <div class="conleft">您好，欢迎来到排班管理后台。</div>
      <div class="conright">
        <img src="@/assets/images/newtimer.png" alt="" class="newtimer" />
        {{ formattedTime }}
      </div>
    </div>
    <div class="conbt">
      <div class="containermain">
        <div class="containermaintop">
          <div class="containermaintitle">全院今日排班</div>
          <div class="containermaintbox">
            <div class="containermainitem">
              <div class="containermainitemtitle">
                <img
                  src="@/assets/images/containermainitemtitleicon.png"
                  alt=""
                  class="containermainitemtitleicon"
                />
                预约人数
              </div>
              <div class="containermainitemname">{{ patientnumber }}</div>
            </div>
            <div class="containermainitem containermainitems">
              <div class="containermainitemtitle">
                <img
                  src="@/assets/images/containermainitemtitleicon.png"
                  alt=""
                  class="containermainitemtitleicon"
                />
                排班治疗师
              </div>
              <div class="containermainitemname">{{
                therapistnumber
              }}</div></div
            >
          </div>
        </div>
        <div class="containermaintop">
          <div class="containermaintitle">治疗师接待排行榜</div>
          <div class="containerphbox">
            <div class="containerphitembt">
              <div>序号</div>
              <div>姓名</div>
              <div>接待数量</div>
            </div>

            <div
              class="containerphitembts"
              v-for="(item, index) in therapistRankdata"
              :key="item"
              :class="
                index === 0
                  ? 'f1'
                  : index === 1
                  ? 'f2'
                  : index === 2
                  ? 'f3'
                  : ''
              "
            >
              <div>
                <!-- <img
                  :src="`/src/assets/images/f${index + 1}.png`"
                  alt=""
                  class="f1img"
                  v-if="index < 3"
                />
                <div class="orlast" v-else>{{ index + 1 }}</div> -->
                <div class="orlast"> {{ index + 1 }}</div>
              </div>
              <div class="containerphitemname">{{ item.therapistName }}</div>
              <div class="containerphitemvalue">{{ item.number }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 主题部分 -->
      <div class="containerrightbox">
        <div class="maindatabt">今日各组接待</div>
        <div class="maindatades">
          <div class="oldbox">
            <img src="@/assets/images/olde.png" alt="" class="oldimg" />
            已结束：{{ dayNumberdata.finish }}人
          </div>
          <div class="oldbox">
            <img src="@/assets/images/newe.png" alt="" class="oldimgw" />
            未开始：{{ dayNumberdata.noFinish }}人
          </div>
          <div class="oldbox">
            <img src="@/assets/images/nosin.png" alt="" class="oldimg" />
            未到：{{ dayNumberdata.noSign }}人
          </div>
        </div>
        <div class="dayadminboxsy">
          <div class="dayleftboxsy">
            <div class="daylefttopsy">时间段</div>
            <div class="dayleftbottom"
              >今日各组接待
              <div
                v-for="item in Sjdata"
                :key="item.GroupName"
                class="dayleftbottomitem"
              >
                {{ item.groupName || item.attribute }}：{{ item.number }}人
              </div>
            </div>
          </div>
          <div class="dayrightboxsy">
            <!-- 时间段 -->
            <!--  时间段分组 -->
            <div class="fzboxsy beautifulScroll">
              <div class="dayrighttopsy">
                <div
                  :class="getTimeClass(item)"
                  class="daytimeitemsy"
                  v-for="item in timeList"
                  :key="item"
                  >{{ item }}</div
                >
              </div>
              <div class="dayrightmainsy">
                <div
                  class="daytimemainsy"
                  v-for="(item, index) in timeList"
                  :key="index"
                  :class="getTimeClass(item)"
                >
                  <!-- 每个 daytimemain 内的内容 -->
                  <div
                    v-for="(groupName, idx) in getGroupNamesForTimeRange(item)"
                    :key="idx"
                    class="daytimemainitemsy"
                  >
                    <div v-if="groupName.number != null">
                      {{ groupName.name }}：{{ groupName.number }}人</div
                    >
                  </div>
                </div>
              </div>
            </div>
            <div class="dayrightbottomsy" @click="godd">
              <div>待定组</div>
              <div class="dayrightbottomsy1">{{ waitNumbers }} 人</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import {
    patientNumber,
    therapistNumber,
    therapistRank,
    dayNumber,
  } from '@/api/index';
  import { useSelectionStore, useUserStore } from '@/store';
  import { storeToRefs } from 'pinia';
  import {
    monthPlan,
    dayGroupPlan,
    dayAttributePlan,
    dayIntervalPlan,
    monthAttributePlan,
    getParent,
    getTimeList,
    waitNumber,
    patientIfo,
    schemeList,
  } from '@/api/restList.ts';
  import router from '@/router';

  const getTimeClass = (item) => {
    const [startTime, endTime] = item.split('-');
    const now = new Date();
    const start = new Date();
    const end = new Date();

    // 设置当前日期的时间
    start.setHours(...startTime.split(':'));
    end.setHours(...endTime.split(':'));

    // 判断当前时间
    if (now >= start && now < end) {
      return 'during'; // 当前时间在时间段内
    } else if (now < start) {
      return 'new'; // 当前时间在时间段之前
    } else {
      return 'old'; // 当前时间在时间段之后
    }
  };

  // 定义时间段
  const timeList = ref();
  //统计data
  const dayNumberdata = ref({
    finish: 0,
    noFinish: 0,
  });
  // 处理时间列表数据相关参数
  const userStore = useUserStore();
  // 获取用户身份的数据
  const userdata = storeToRefs(userStore);
  const userinfo = ref();
  userinfo.value = userdata;

  // 定义待定组数据
  const waitNumbers = ref(0);
  // 定义今天数据
  const daysPb = ref();
  // 定义各组 统计
  const Sjdata = ref();
  // 查询数据
  const fetchData = () => {
    if (
      userinfo.value.roleName == '超级管理员' ||
      userinfo.value.roleName == '主任'
    ) {
      dayGroupPlan({
        date: datevalue.value,
      }).then((res: any) => {
        if (res.code == 200) {
          daysPb.value = res.data;
        }
      });
      monthPlan({ startDate: datevalue.value, endDate: datevalue.value }).then(
        (res: any) => {
          // console.log('查询今日各组排班', res.data);
          Sjdata.value = res.data[datevalue.value];
        }
      );
    } else {
      getParent({
        id: userinfo.value.organization[0].organizationId,
      }).then((res: any) => {
        if (res.code == 200) {
          dayAttributePlan({
            date: datevalue.value,
            groupName: res.data.organizationId,
          }).then((ress: any) => {
            daysPb.value = ress.data;
          });

          monthAttributePlan({
            startDate: datevalue.value,
            endDate: datevalue.value,
            groupName: res.data.organizationId,
          }).then((resd: any) => {
            // console.log('查询今日各组排班', res.data);
            Sjdata.value = resd.data[datevalue.value];
          });
        }
      });
    }
  };

  const getGroupNamesForTimeRange = (range) => {
    const [start, end] = range.split('-');

    // 确保数据存在
    if (!daysPb.value) {
      return [];
    }

    // 使用对象来统计每个时间点的分组数量
    const timeGroupCount = {};

    // 遍历数据以统计每个时间的分组数量
    daysPb.value.forEach((data) => {
      const currentTime = data.time;
      if (!timeGroupCount[currentTime]) {
        timeGroupCount[currentTime] = 0;
      }
      timeGroupCount[currentTime]++;
    });

    // 找到所有时间点中的最大数量
    const maxGroupCount = Math.max(...Object.values(timeGroupCount));

    // 获取当前时间段的分组，包含原有数据
    const groupNames = daysPb.value
      .filter((data) => data.time >= start && data.time <= end) // 选择当前时间段的项
      .map((data) => ({
        id: data.groupName || data.attribute,
        game: data.gname,
        name: data.gname || data.aname,
        number: data.number,
        time: data.time,
        timer: range,
      }));

    // 填充空数据以确保数量一致
    while (groupNames.length < maxGroupCount + 5) {
      groupNames.push({ name: '', id: null }); // 添加空数据
    }

    return groupNames;
  };

  // const getGroupNamesForTimeRange = (range) => {
  //   const [start, end] = range.split('-');

  //   // 过滤出符合时间区间的 gname 和 id
  //   if (!daysPb.value) {
  //     return;
  //   }
  //   const groupNames = daysPb.value
  //     .filter((data) => {
  //       const currentTime = data.time;
  //       // 直接比较字符串
  //       return currentTime >= start && currentTime <= end;
  //     })
  //     .map((data) => {
  //       return {
  //         id: data.groupName,
  //         game: data.gname,
  //         name: data.gname,
  //         number: data.number,
  //         time: data.time,
  //         timer: start + '-' + end,
  //       };
  //     });

  //   // 返回结果：没有符合的返回空数组
  //   return groupNames.length > 0 ? groupNames : [{ name: '', id: null }];
  // };
  const formattedTime = ref(''); // 用于显示格式化的时间
  const timer = ref();

  const patientnumber = ref(0);
  const therapistnumber = ref(0);
  const therapistRankdata = ref();
  // 获取数据
  const freach = () => {
    waitNumber().then((res) => {
      if (res.code == 200) {
        waitNumbers.value = res.data;
      }
    });
    getTimeList().then((res) => {
      if (res.code == 200) {
        timeList.value = res.data;
      }
    });
    patientNumber().then((res: any) => {
      if (res.code == 200) {
        patientnumber.value = res.data;
      }
    });
    therapistNumber().then((res: any) => {
      if (res.code == 200) {
        therapistnumber.value = res.data;
      }
    });
    therapistRank().then((res: any) => {
      if (res.code == 200) {
        therapistRankdata.value = res.data;
      }
    });
    dayNumber().then((res: any) => {
      if (res.code == 200) {
        dayNumberdata.value = res.data;
      }
    });
  };
  freach();
  const datevalue = ref();
  // 格式化时间函数
  const formatTime = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    datevalue.value = `${year}-${month}-${day}`;
    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  };

  // 更新时间
  const updateTime = () => {
    const now = new Date();
    formattedTime.value = formatTime(now);
  };

  // 挂载时启动定时器
  onMounted(() => {
    updateTime(); // 初始化时更新一次
    fetchData();
    timer.value = setInterval(updateTime, 1000); // 每秒更新
  });

  // 组件卸载时清除定时器
  onUnmounted(() => {
    if (timer.value) {
      clearInterval(timer.value);
    }
  });

  // 去待定分组

  const godd = () => {
    router.push({
      name: 'waitList',
    });
  };
</script>

<style lang="less" scoped>
  .containerhome {
    // position: absolute;
    // top: 60px;
    width: 100%;
    height: 100%;
    // left: 0px;
    // background-color: red;
    display: flex;
    flex-direction: column;
    background-color: #fff;
  }
  .container {
    background-color: var(--color-fill-2);
    padding: 16px 20px;
    padding-bottom: 0;
    display: flex;
  }

  .left-side {
    flex: 1;
    overflow: auto;
  }

  .right-side {
    width: 280px;
    margin-left: 16px;
  }

  .panel {
    background-color: var(--color-bg-2);
    border-radius: 4px;
    overflow: auto;
  }
  :deep(.panel-border) {
    margin-bottom: 0;
    border-bottom: 1px solid rgb(var(--gray-2));
  }
  .moduler-wrap {
    border-radius: 4px;
    background-color: var(--color-bg-2);
    :deep(.text) {
      font-size: 12px;
      text-align: center;
      color: rgb(var(--gray-8));
    }

    :deep(.wrapper) {
      margin-bottom: 8px;
      text-align: center;
      cursor: pointer;

      &:last-child {
        .text {
          margin-bottom: 0;
        }
      }
      &:hover {
        .icon {
          color: rgb(var(--arcoblue-6));
          background-color: #e8f3ff;
        }
        .text {
          color: rgb(var(--arcoblue-6));
        }
      }
    }

    :deep(.icon) {
      display: inline-block;
      width: 32px;
      height: 32px;
      margin-bottom: 4px;
      color: rgb(var(--dark-gray-1));
      line-height: 32px;
      font-size: 16px;
      text-align: center;
      background-color: rgb(var(--gray-1));
      border-radius: 4px;
    }
  }
</style>

<style lang="less" scoped>
  // responsive
  .mobile {
    .container {
      display: block;
    }
    .right-side {
      // display: none;
      width: 100%;
      margin-left: 0;
      margin-top: 16px;
    }
  }
</style>
